from django.shortcuts import render
from rest_framework import viewsets,mixins
from .serializers import ArticleListSerializers,ArticleCreateSerializers,CollectSerializers,CollectListSerializers
from .serializers import BlogCommentCreateSerializers,BlogCommentListSerializers
from .models import Article,Comment,CollectArticleModel
from rest_framework.pagination import PageNumberPagination,LimitOffsetPagination
from rest_framework.response import Response
from rest_framework import filters,status
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from notifications.signals import notify
from users.models import UserProfile


class BlogPagination(LimitOffsetPagination):
    limit_query_param = 'limit'
    default_limit = 5


class BlogViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    """
    list:
        获取文章
    create:
        新建文章
    retrieve:
        文章详情
    """
    filter_backends = (filters.SearchFilter,)
    search_fields = ('title', 'author__username',"content")
    pagination_class = BlogPagination
    queryset = Article.objects.all().order_by("-publish_date")
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)
    permission_classes = (IsAuthenticated,)

    def get_serializer_class(self):
        if self.action == "create":
            return ArticleCreateSerializers
        else:
            return ArticleListSerializers


class CommentViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    def get_queryset(self):
        article_id = self.request.query_params.get("article")[0] if self.request.query_params.get("article") else 0
        return Comment.objects.filter(article_id=article_id)

    def get_serializer_class(self):
        if self.action == "create":
            return BlogCommentCreateSerializers
        else:
            return BlogCommentListSerializers

    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)
    permission_classes = (IsAuthenticated,)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        article = serializer.validated_data["article"]
        headers = self.get_success_headers(serializer.data)
        notify.send(request.user, recipient=article.author, verb="{}-评论".format(article.title),
                    description="{}评论:{}".format(self.request.user.username,serializer.validated_data["comment"]),)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class CollectViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,viewsets.GenericViewSet):
    serializer_class = CollectSerializers
    authentication_classes = (JSONWebTokenAuthentication,SessionAuthentication)
    permission_classes = (IsAuthenticated,)

    def get_serializer_class(self):
        if self.action == "create":
            return CollectSerializers
        else :
            return CollectListSerializers

    def get_queryset(self):
        return CollectArticleModel.objects.filter(user=self.request.user)

    def list(self, request, *args, **kwargs):
        if request.query_params.get("blogid"):
            collects = CollectArticleModel.objects.filter(user=request.user, article_id=self.request.query_params.get("blogid")[0])
            if collects:
                return Response({"collect":True})
            else :
                return Response({"collect": False})
        else :
            queryset = self.filter_queryset(self.get_queryset())

            page = self.paginate_queryset(queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True)
                return self.get_paginated_response(serializer.data)

            serializer = self.get_serializer(queryset, many=True)
            return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.request.user
        article = serializer.validated_data["article"]
        collects = CollectArticleModel.objects.filter(user=user,article_id=article)
        if collects:
            collects.delete()
            return Response({"msg":"已取消","collect":False})
        else:
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response({"msg":"已收藏","collect":True}, status=status.HTTP_201_CREATED, headers=headers)


class MyArticleViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
    serializer_class = ArticleListSerializers

    def get_queryset(self):
        return Article.objects.filter(author=self.request.user)
